/* mem_leak.c

   memleak demo

两种方式观察系统内存使用情况：
   1. vmstat 1
   1. pid=$(ps -ef | grep mem_leak | awk '{print $2}' | sed -n '1p'); top -p $pid

使用内存诊断工具
  valgrind --leak-check=yes -v ./mem_leak
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

//
// pid=$(ps -ef | grep mem | awk '{print $2}' | sed -n '1p'); top -p $pid
long long *fibonacci(long long *n0, long long *n1) {
  //分配1024个长整数空间方便观测内存的变化情况
  //   long long *v = (long long *)calloc(1024, sizeof(long long));
  long long *v = (long long *)malloc(1024 * sizeof(long long));
  *v = *n0 + *n1;

  return v;
}

int main(int argc, char const *argv[]) {
  long long n0 = 0;
  long long n1 = 1;
  long long *v = NULL;

  int n = 2;

  for (n = 2; n > 0; n++) {
    v = fibonacci(&n0, &n1);
    n0 = n1;
    n1 = *v;
    printf("%dth => %lld\n", n, *v);

    usleep(500);
  }

  return 0;
}